/**
 * 资源管理路由
 * 提供模型、材质、贴图的依赖关系分析和使用率统计
 */
const express = require('express');
const router = express.Router();
const fs = require('fs').promises;
const path = require('path');
const { PROJECTS_DIR } = require('../utils/constants');
const {
    readProjectsIndex,
    readProjectConfig
} = require('../services/projectService');

/**
 * 获取项目的资源统计和依赖关系
 * GET /api/resources/:projectId/analysis
 */
router.get('/:projectId/analysis', async (req, res) => {
    try {
        const { projectId } = req.params;
        
        // 获取项目信息
        const index = await readProjectsIndex();
        const projectMeta = index.projects.find(p => p.id === projectId);
        
        if (!projectMeta) {
            return res.status(404).json({
                success: false,
                error: '项目不存在'
            });
        }
        
        const projectDir = path.join(PROJECTS_DIR, projectMeta.path);
        const projectConfig = await readProjectConfig(projectMeta.path);
        
        // 读取所有资源
        const models = await loadAllModels(projectDir);
        const materials = await loadAllMaterials(projectDir);
        const textures = await loadAllTextures(projectDir);
        const scenes = await loadAllScenes(projectDir, projectConfig.scenes || []);
        
        // 分析依赖关系
        const analysis = analyzeResourceDependencies(models, materials, textures, scenes);
        
        // 分析场景资源和性能
        const sceneAnalysis = analyzeSceneResources(scenes, models, materials, textures);
        
        res.json({
            success: true,
            data: {
                projectId,
                projectName: projectMeta.name,
                ...analysis,
                sceneAnalysis
            }
        });
        
    } catch (error) {
        console.error('❌ 资源分析失败:', error);
        res.status(500).json({
            success: false,
            error: error.message
        });
    }
});

/**
 * 获取未使用的资源列表
 * GET /api/resources/:projectId/unused
 */
router.get('/:projectId/unused', async (req, res) => {
    try {
        const { projectId } = req.params;
        
        const index = await readProjectsIndex();
        const projectMeta = index.projects.find(p => p.id === projectId);
        
        if (!projectMeta) {
            return res.status(404).json({
                success: false,
                error: '项目不存在'
            });
        }
        
        const projectDir = path.join(PROJECTS_DIR, projectMeta.path);
        const projectConfig = await readProjectConfig(projectMeta.path);
        
        const models = await loadAllModels(projectDir);
        const materials = await loadAllMaterials(projectDir);
        const textures = await loadAllTextures(projectDir);
        const scenes = await loadAllScenes(projectDir, projectConfig.scenes || []);
        
        const analysis = analyzeResourceDependencies(models, materials, textures, scenes);
        
        // 提取未使用的资源
        const unusedResources = {
            models: analysis.models.filter(m => !m.usedInScenes),
            materials: analysis.materials.filter(m => !m.usedByModels),
            textures: analysis.textures.filter(t => !t.usedByMaterials)
        };
        
        res.json({
            success: true,
            data: unusedResources
        });
        
    } catch (error) {
        console.error('❌ 获取未使用资源失败:', error);
        res.status(500).json({
            success: false,
            error: error.message
        });
    }
});

/**
 * 获取资源的详细依赖信息
 * GET /api/resources/:projectId/:resourceType/:resourceId/dependencies
 */
router.get('/:projectId/:resourceType/:resourceId/dependencies', async (req, res) => {
    try {
        const { projectId, resourceType, resourceId } = req.params;
        
        const index = await readProjectsIndex();
        const projectMeta = index.projects.find(p => p.id === projectId);
        
        if (!projectMeta) {
            return res.status(404).json({
                success: false,
                error: '项目不存在'
            });
        }
        
        const projectDir = path.join(PROJECTS_DIR, projectMeta.path);
        const projectConfig = await readProjectConfig(projectMeta.path);
        
        const models = await loadAllModels(projectDir);
        const materials = await loadAllMaterials(projectDir);
        const textures = await loadAllTextures(projectDir);
        const scenes = await loadAllScenes(projectDir, projectConfig.scenes || []);
        
        const dependencies = getResourceDependencies(
            resourceType,
            resourceId,
            models,
            materials,
            textures,
            scenes
        );
        
        res.json({
            success: true,
            data: dependencies
        });
        
    } catch (error) {
        console.error('❌ 获取资源依赖失败:', error);
        res.status(500).json({
            success: false,
            error: error.message
        });
    }
});

// ============================================
// 辅助函数
// ============================================

/**
 * 加载所有模型
 */
async function loadAllModels(projectDir) {
    const modelsDir = path.join(projectDir, 'models');
    const models = [];
    
    try {
        const files = await fs.readdir(modelsDir);
        
        for (const file of files) {
            if (file.endsWith('.json')) {
                const filePath = path.join(modelsDir, file);
                const content = await fs.readFile(filePath, 'utf-8');
                models.push(JSON.parse(content));
            }
        }
    } catch (error) {
        if (error.code !== 'ENOENT') {
            console.warn('⚠️ 读取模型目录失败:', error.message);
        }
    }
    
    return models;
}

/**
 * 加载所有材质
 */
async function loadAllMaterials(projectDir) {
    const materialsDir = path.join(projectDir, 'materials');
    const materials = [];
    
    try {
        const files = await fs.readdir(materialsDir);
        
        for (const file of files) {
            if (file.endsWith('.json')) {
                const filePath = path.join(materialsDir, file);
                const content = await fs.readFile(filePath, 'utf-8');
                materials.push(JSON.parse(content));
            }
        }
    } catch (error) {
        if (error.code !== 'ENOENT') {
            console.warn('⚠️ 读取材质目录失败:', error.message);
        }
    }
    
    return materials;
}

/**
 * 加载所有贴图
 */
async function loadAllTextures(projectDir) {
    const texturesDir = path.join(projectDir, 'textures');
    const textures = [];
    
    try {
        const files = await fs.readdir(texturesDir);
        
        for (const file of files) {
            if (file.endsWith('.json')) {
                const filePath = path.join(texturesDir, file);
                const content = await fs.readFile(filePath, 'utf-8');
                textures.push(JSON.parse(content));
            }
        }
    } catch (error) {
        if (error.code !== 'ENOENT') {
            console.warn('⚠️ 读取贴图目录失败:', error.message);
        }
    }
    
    return textures;
}

/**
 * 加载所有场景
 */
async function loadAllScenes(projectDir, sceneMetadatas) {
    const scenes = [];
    const fsSync = require('fs');
    
    for (const sceneMeta of sceneMetadatas) {
        try {
            const sceneConfigPath = path.join(projectDir, sceneMeta.sceneFile);
            const content = await fs.readFile(sceneConfigPath, 'utf-8');
            const sceneData = JSON.parse(content);
            
            // 读取场景的nodes.json文件（如果存在）
            const sceneDir = path.dirname(sceneConfigPath);
            const nodesPath = path.join(sceneDir, 'nodes.json');
            
            try {
                const nodesContent = await fs.readFile(nodesPath, 'utf-8');
                const nodesData = JSON.parse(nodesContent);
                sceneData.nodes = nodesData.nodes || [];
            } catch (error) {
                // nodes.json不存在或读取失败，使用旧的objects结构
                sceneData.nodes = [];
            }
            
            // 🌍 读取场景的环境配置（environment.json）
            const environmentPath = path.join(sceneDir, 'environment.json');
            try {
                const envContent = await fs.readFile(environmentPath, 'utf-8');
                const envData = JSON.parse(envContent);
                sceneData.environment = envData;
                
                // 如果有环境模型，获取模型文件信息
                if (envData.environmentModel && envData.environmentModel.filename) {
                    const envModelPath = path.join(sceneDir, 'environment', envData.environmentModel.filename);
                    if (fsSync.existsSync(envModelPath)) {
                        const stats = fsSync.statSync(envModelPath);
                        sceneData.environment.environmentModel.fileSize = stats.size;
                        sceneData.environment.environmentModel.filePath = envModelPath;
                    }
                }
            } catch (error) {
                // environment.json不存在，使用默认配置
                sceneData.environment = null;
            }
            
            scenes.push(sceneData);
        } catch (error) {
            console.warn(`⚠️ 读取场景失败 (${sceneMeta.name}):`, error.message);
        }
    }
    
    return scenes;
}

/**
 * 分析资源依赖关系
 */
function analyzeResourceDependencies(models, materials, textures, scenes) {
    // 统计使用情况
    const materialUsageMap = new Map(); // 材质被哪些模型使用
    const textureUsageMap = new Map(); // 贴图被哪些材质使用
    const modelUsageMap = new Map(); // 模型被哪些场景使用
    
    // 分析模型使用的材质
    models.forEach(model => {
        if (model.meshMaterials) {
            // ✅ 新架构：meshMaterials 格式为 { "meshName": "materialName" }
            Object.entries(model.meshMaterials).forEach(([meshName, materialName]) => {
                if (materialName) {
                    // 根据材质名查找材质ID
                    const material = materials.find(m => m.displayName === materialName);
                    if (material) {
                        if (!materialUsageMap.has(material.id)) {
                            materialUsageMap.set(material.id, []);
                        }
                        materialUsageMap.get(material.id).push({
                            modelId: model.id,
                            modelName: model.displayName || model.name,
                            meshName: meshName
                        });
                    }
                }
            });
        }
    });
    
    // 分析贴图被材质引用的情况（直接从贴图的referencedBy字段读取）
    textures.forEach(texture => {
        if (texture.referencedBy && Array.isArray(texture.referencedBy)) {
            texture.referencedBy.forEach(materialId => {
                const material = materials.find(m => m.id === materialId);
                if (material) {
                    if (!textureUsageMap.has(texture.id)) {
                        textureUsageMap.set(texture.id, []);
                    }
                    
                    // 找出材质中哪个字段使用了这个贴图
                    const textureFields = ['map', 'normalMap', 'bumpMap', 'aoMap', 'roughnessMap', 'metalnessMap'];
                    let textureType = 'unknown';
                    
                    // 准备多种匹配值
                    const matchValues = [
                        texture.id,
                        texture.name,
                        texture.displayName,
                        texture.filename ? texture.filename.replace(/\.[^/.]+$/, '') : null
                    ].filter(Boolean);
                    
                    for (const field of textureFields) {
                        if (material[field] && matchValues.includes(material[field])) {
                            textureType = field;
                            break;
                        }
                    }
                    
                    textureUsageMap.get(texture.id).push({
                        materialId: material.id,
                        materialName: material.displayName || material.name,
                        textureType: textureType
                    });
                }
            });
        }
    });
    
    // 分析场景使用的模型
    scenes.forEach(scene => {
        // 从nodes数组中提取模型引用（新结构）
        if (scene.nodes && Array.isArray(scene.nodes)) {
            scene.nodes.forEach(node => {
                if (node.components && Array.isArray(node.components)) {
                    node.components.forEach(component => {
                        if (component.type === 'model' && component.modelId) {
                            if (!modelUsageMap.has(component.modelId)) {
                                modelUsageMap.set(component.modelId, []);
                            }
                            modelUsageMap.get(component.modelId).push({
                                sceneId: scene.id,
                                sceneName: scene.name,
                                objectName: node.name || component.modelName
                            });
                        }
                    });
                }
            });
        }
        
        // 兼容旧的objects结构
        if (scene.objects && Array.isArray(scene.objects)) {
            scene.objects.forEach(obj => {
                if (obj.modelId) {
                    if (!modelUsageMap.has(obj.modelId)) {
                        modelUsageMap.set(obj.modelId, []);
                    }
                    modelUsageMap.get(obj.modelId).push({
                        sceneId: scene.id,
                        sceneName: scene.name,
                        objectName: obj.name
                    });
                }
            });
        }
    });
    
    // 构建资源列表（包含使用情况）
    const modelsWithUsage = models.map(model => {
        const usageInfo = modelUsageMap.get(model.id) || [];
        const materialIds = new Set();
        
        if (model.meshMaterials) {
            // ✅ 新架构：meshMaterials 格式为 { "meshName": "materialName" }
            Object.values(model.meshMaterials).forEach(materialName => {
                if (materialName) {
                    // 根据材质名查找材质ID
                    const material = materials.find(m => m.displayName === materialName);
                    if (material) {
                        materialIds.add(material.id);
                    }
                }
            });
        }
        
        return {
            id: model.id,
            name: model.displayName || model.name,
            filename: model.filename,
            size: model.size,
            format: model.format,
            usedInScenes: usageInfo.length > 0,
            sceneUsage: usageInfo,
            materials: Array.from(materialIds),
            materialCount: materialIds.size
        };
    });
    
    const materialsWithUsage = materials.map(material => {
        const usageInfo = materialUsageMap.get(material.id) || [];
        const textureIds = [];
        const textureFields = ['map', 'normalMap', 'bumpMap', 'aoMap', 'roughnessMap', 'metalnessMap'];
        
        textureFields.forEach(field => {
            if (material[field]) {
                textureIds.push({
                    id: material[field],
                    type: field
                });
            }
        });
        
        return {
            id: material.id,
            name: material.displayName || material.name,
            color: material.color,
            metalness: material.metalness,
            roughness: material.roughness,
            usedByModels: usageInfo.length > 0,
            modelUsage: usageInfo,
            textures: textureIds,
            textureCount: textureIds.length
        };
    });
    
    const texturesWithUsage = textures.map(texture => {
        const usageInfo = textureUsageMap.get(texture.id) || [];
        
        // 判断是否被使用：优先使用textureUsageMap，备用检查referencedBy字段
        const isUsed = usageInfo.length > 0 || 
                       (texture.referencedBy && texture.referencedBy.length > 0);
        
        return {
            id: texture.id,
            name: texture.displayName || texture.name,
            filename: texture.filename,
            size: texture.size,
            mimetype: texture.mimetype,
            width: texture.width,
            height: texture.height,
            usedByMaterials: isUsed,
            materialUsage: usageInfo,
            // 保留原始引用信息供调试
            referencedBy: texture.referencedBy || [],
            referenceCount: texture.referenceCount || 0
        };
    });
    
    // 计算使用率
    const statistics = {
        models: {
            total: models.length,
            used: modelsWithUsage.filter(m => m.usedInScenes).length,
            unused: modelsWithUsage.filter(m => !m.usedInScenes).length,
            usageRate: models.length > 0 
                ? ((modelsWithUsage.filter(m => m.usedInScenes).length / models.length) * 100).toFixed(2) + '%'
                : '0%'
        },
        materials: {
            total: materials.length,
            used: materialsWithUsage.filter(m => m.usedByModels).length,
            unused: materialsWithUsage.filter(m => !m.usedByModels).length,
            usageRate: materials.length > 0
                ? ((materialsWithUsage.filter(m => m.usedByModels).length / materials.length) * 100).toFixed(2) + '%'
                : '0%'
        },
        textures: {
            total: textures.length,
            used: texturesWithUsage.filter(t => t.usedByMaterials).length,
            unused: texturesWithUsage.filter(t => !t.usedByMaterials).length,
            usageRate: textures.length > 0
                ? ((texturesWithUsage.filter(t => t.usedByMaterials).length / textures.length) * 100).toFixed(2) + '%'
                : '0%'
        },
        scenes: {
            total: scenes.length
        }
    };
    
    return {
        statistics,
        models: modelsWithUsage,
        materials: materialsWithUsage,
        textures: texturesWithUsage
    };
}

/**
 * 获取特定资源的依赖信息
 */
function getResourceDependencies(resourceType, resourceId, models, materials, textures, scenes) {
    const dependencies = {
        resourceType,
        resourceId,
        dependsOn: [], // 该资源依赖的资源
        usedBy: [] // 使用该资源的资源
    };
    
    switch (resourceType) {
        case 'model':
            const model = models.find(m => m.id === resourceId);
            if (model) {
                // 模型依赖的材质
                if (model.meshMaterials) {
                    const materialIds = new Set();
                    // ✅ 新架构：meshMaterials 格式为 { "meshName": "materialName" }
                    Object.values(model.meshMaterials).forEach(materialName => {
                        if (materialName) {
                            // 根据材质名查找材质
                            const material = materials.find(m => m.displayName === materialName);
                            if (material) {
                                materialIds.add(material.id);
                            }
                        }
                    });
                    
                    materialIds.forEach(matId => {
                        const material = materials.find(m => m.id === matId);
                        if (material) {
                            dependencies.dependsOn.push({
                                type: 'material',
                                id: material.id,
                                name: material.displayName || material.name
                            });
                        }
                    });
                }
                
                // 哪些场景使用了该模型
                scenes.forEach(scene => {
                    // 从nodes数组中查找（新结构）
                    if (scene.nodes && Array.isArray(scene.nodes)) {
                        scene.nodes.forEach(node => {
                            if (node.components && Array.isArray(node.components)) {
                                node.components.forEach(component => {
                                    if (component.type === 'model' && component.modelId === resourceId) {
                                        dependencies.usedBy.push({
                                            type: 'scene',
                                            id: scene.id,
                                            name: scene.name,
                                            objectName: node.name || component.modelName
                                        });
                                    }
                                });
                            }
                        });
                    }
                    
                    // 兼容旧的objects结构
                    if (scene.objects && Array.isArray(scene.objects)) {
                        scene.objects.forEach(obj => {
                            if (obj.modelId === resourceId) {
                                dependencies.usedBy.push({
                                    type: 'scene',
                                    id: scene.id,
                                    name: scene.name,
                                    objectName: obj.name
                                });
                            }
                        });
                    }
                });
            }
            break;
            
        case 'material':
            const material = materials.find(m => m.id === resourceId);
            if (material) {
                // 材质依赖的贴图
                const textureFields = ['map', 'normalMap', 'bumpMap', 'aoMap', 'roughnessMap', 'metalnessMap'];
                textureFields.forEach(field => {
                    if (material[field]) {
                        // 尝试多种匹配方式：ID、name、displayName、文件名（不含扩展名）
                        const texture = textures.find(t => {
                            if (t.id === material[field]) return true;
                            if (t.name === material[field]) return true;
                            if (t.displayName === material[field]) return true;
                            const nameWithoutExt = t.filename ? t.filename.replace(/\.[^/.]+$/, '') : null;
                            if (nameWithoutExt === material[field]) return true;
                            return false;
                        });
                        
                        if (texture) {
                            dependencies.dependsOn.push({
                                type: 'texture',
                                id: texture.id,
                                name: texture.displayName || texture.name,
                                textureType: field
                            });
                        }
                    }
                });
                
                // 哪些模型使用了该材质
                models.forEach(model => {
                    if (model.meshMaterials) {
                        // ✅ 新架构：meshMaterials 格式为 { "meshName": "materialName" }
                        Object.entries(model.meshMaterials).forEach(([meshName, materialName]) => {
                            // 根据材质名查找材质，检查是否匹配当前资源
                            const mat = materials.find(m => m.id === resourceId);
                            if (mat && mat.displayName === materialName) {
                                dependencies.usedBy.push({
                                    type: 'model',
                                    id: model.id,
                                    name: model.displayName || model.name,
                                    meshName: meshName
                                });
                            }
                        });
                    }
                });
            }
            break;
            
        case 'texture':
            // 从贴图的 referencedBy 字段获取引用该贴图的材质
            const texture = textures.find(t => t.id === resourceId);
            if (texture && texture.referencedBy && Array.isArray(texture.referencedBy)) {
                texture.referencedBy.forEach(materialId => {
                    const material = materials.find(m => m.id === materialId);
                    if (material) {
                        // 找出材质中哪个字段使用了这个贴图
                        const textureFields = ['map', 'normalMap', 'bumpMap', 'aoMap', 'roughnessMap', 'metalnessMap'];
                        let textureType = 'unknown';
                        
                        // 准备多种匹配值
                        const matchValues = [
                            texture.id,
                            texture.name,
                            texture.displayName,
                            texture.filename ? texture.filename.replace(/\.[^/.]+$/, '') : null
                        ].filter(Boolean);
                        
                        for (const field of textureFields) {
                            if (material[field] && matchValues.includes(material[field])) {
                                textureType = field;
                                break;
                            }
                        }
                        
                        dependencies.usedBy.push({
                            type: 'material',
                            id: material.id,
                            name: material.displayName || material.name,
                            textureType: textureType
                        });
                    }
                });
            }
            break;
    }
    
    return dependencies;
}

/**
 * 分析场景资源使用和性能
 */
function analyzeSceneResources(scenes, models, materials, textures) {
    const sceneResourceMap = [];
    
    scenes.forEach(scene => {
        // 收集场景使用的模型ID
        const usedModelIds = new Set();
        
        // 从nodes数组中提取模型引用（新结构）
        if (scene.nodes && Array.isArray(scene.nodes)) {
            scene.nodes.forEach(node => {
                if (node.components && Array.isArray(node.components)) {
                    node.components.forEach(component => {
                        if (component.type === 'model' && component.modelId) {
                            usedModelIds.add(component.modelId);
                        }
                    });
                }
            });
        }
        
        // 兼容旧的objects结构
        if (scene.objects && Array.isArray(scene.objects)) {
            scene.objects.forEach(obj => {
                if (obj.modelId) {
                    usedModelIds.add(obj.modelId);
                }
            });
        }
        
        // 收集场景使用的模型详情
        const usedModels = [];
        const usedMaterialIds = new Set();
        let totalModelSize = 0;
        
        usedModelIds.forEach(modelId => {
            const model = models.find(m => m.id === modelId);
            if (model) {
                usedModels.push({
                    id: model.id,
                    name: model.displayName || model.name,
                    filename: model.filename,
                    size: model.size,
                    format: model.format
                });
                totalModelSize += model.size || 0;
                
                // 收集模型使用的材质
                if (model.meshMaterials) {
                    // ✅ 新架构：meshMaterials 格式为 { "meshName": "materialName" }
                    Object.values(model.meshMaterials).forEach(materialName => {
                        if (materialName) {
                            // 根据材质名查找材质ID
                            const material = materials.find(m => m.displayName === materialName);
                            if (material) {
                                usedMaterialIds.add(material.id);
                            }
                        }
                    });
                }
            }
        });
        
        // 🌍 收集场景的环境模型信息
        let environmentModel = null;
        if (scene.environment && scene.environment.environmentModel && scene.environment.environmentModel.filename) {
            const envModel = scene.environment.environmentModel;
            environmentModel = {
                filename: envModel.filename,
                size: envModel.fileSize || 0,
                position: envModel.position || { x: 0, y: 0, z: 0 },
                rotation: envModel.rotation || { x: 0, y: 0, z: 0 },
                scale: envModel.scale || { x: 1, y: 1, z: 1 },
                type: 'environment'
            };
            totalModelSize += envModel.fileSize || 0;
        }
        
        // 收集场景使用的材质详情
        const usedMaterials = [];
        const usedTextureIds = new Set();
        
        usedMaterialIds.forEach(materialId => {
            const material = materials.find(m => m.id === materialId);
            if (material) {
                usedMaterials.push({
                    id: material.id,
                    name: material.displayName || material.name,
                    color: material.color
                });
                
                // 收集材质使用的贴图（使用材质中的贴图字段）
                const textureFields = ['map', 'normalMap', 'bumpMap', 'aoMap', 'roughnessMap', 'metalnessMap'];
                textureFields.forEach(field => {
                    if (material[field]) {
                        usedTextureIds.add(material[field]);
                    }
                });
            }
        });
        
        // 也可以从贴图的 referencedBy 反向验证
        // 这里我们使用材质的字段来收集贴图ID，因为这是实际使用关系
        
        // 收集场景使用的贴图详情
        const usedTextures = [];
        let totalTextureSize = 0;
        
        usedTextureIds.forEach(textureId => {
            // 尝试多种匹配方式：ID、name、displayName、文件名（不含扩展名）
            const texture = textures.find(t => {
                if (t.id === textureId) return true;
                if (t.name === textureId) return true;
                if (t.displayName === textureId) return true;
                // 尝试匹配文件名（不含扩展名）
                const nameWithoutExt = t.filename ? t.filename.replace(/\.[^/.]+$/, '') : null;
                if (nameWithoutExt === textureId) return true;
                return false;
            });
            
            if (texture) {
                usedTextures.push({
                    id: texture.id,
                    name: texture.displayName || texture.name,
                    filename: texture.filename,
                    size: texture.size,
                    mimetype: texture.mimetype
                });
                totalTextureSize += texture.size || 0;
            }
        });
        
        // 计算总大小和性能指标
        const totalSize = totalModelSize + totalTextureSize;
        const resourceCount = usedModels.length + usedMaterials.length + usedTextures.length;
        
        // 🌍 如果有环境模型，在性能分析中单独标注
        const environmentModelSize = environmentModel ? environmentModel.size : 0;
        const totalSizeWithEnv = totalSize + environmentModelSize;
        
        // 估算加载时间（基于文件大小和资源数量）
        // 假设：1MB = 100ms基础时间 + 每个资源20ms + 环境模型加载时间
        const estimatedLoadTime = Math.round(
            (totalSizeWithEnv / 1024 / 1024) * 100 + 
            resourceCount * 20 + 
            (environmentModel ? 50 : 0) // 环境模型额外的初始化时间
        );
        
        // 性能评分（0-100）
        let performanceScore = 100;
        
        // 根据总大小扣分（超过10MB开始扣分）
        if (totalSize > 10 * 1024 * 1024) {
            performanceScore -= Math.min(30, (totalSize / 1024 / 1024 - 10) * 2);
        }
        
        // 🌍 环境模型大小扣分（超过5MB开始扣分，因为环境模型通常较大）
        if (environmentModelSize > 5 * 1024 * 1024) {
            performanceScore -= Math.min(10, (environmentModelSize / 1024 / 1024 - 5) * 1);
        }
        
        // 根据资源数量扣分（超过50个开始扣分）
        if (resourceCount > 50) {
            performanceScore -= Math.min(20, (resourceCount - 50) * 0.5);
        }
        
        // 根据模型数量扣分（超过20个开始扣分）
        if (usedModels.length > 20) {
            performanceScore -= Math.min(15, (usedModels.length - 20) * 1);
        }
        
        // 根据贴图数量和大小扣分
        if (usedTextures.length > 15) {
            performanceScore -= Math.min(15, (usedTextures.length - 15) * 1);
        }
        
        performanceScore = Math.max(0, Math.round(performanceScore));
        
        // 性能等级和建议
        let performanceLevel = 'excellent';
        let performanceSuggestions = [];
        
        if (performanceScore >= 90) {
            performanceLevel = 'excellent';
            performanceSuggestions.push('场景性能优秀，无需优化');
        } else if (performanceScore >= 70) {
            performanceLevel = 'good';
            if (totalSize > 10 * 1024 * 1024) {
                performanceSuggestions.push('考虑压缩大型贴图文件');
            }
            if (usedModels.length > 15) {
                performanceSuggestions.push('模型数量较多，考虑使用LOD优化');
            }
            // 🌍 环境模型优化建议
            if (environmentModelSize > 10 * 1024 * 1024) {
                performanceSuggestions.push('环境模型较大，建议优化模型或使用低多边形版本');
            }
        } else if (performanceScore >= 50) {
            performanceLevel = 'fair';
            if (totalSize > 20 * 1024 * 1024) {
                performanceSuggestions.push('总文件大小偏大，建议优化资源');
            }
            if (usedTextures.length > 20) {
                performanceSuggestions.push('贴图数量过多，考虑使用纹理图集');
            }
            if (usedModels.length > 25) {
                performanceSuggestions.push('模型数量过多，考虑合并或分批加载');
            }
            // 🌍 环境模型优化建议
            if (environmentModelSize > 8 * 1024 * 1024) {
                performanceSuggestions.push('环境模型偏大，建议简化模型或移除不必要的细节');
            }
        } else {
            performanceLevel = 'poor';
            performanceSuggestions.push('场景资源过多，严重影响性能');
            performanceSuggestions.push('建议：减少资源数量、压缩文件、使用分批加载');
            if (totalTextureSize > 15 * 1024 * 1024) {
                performanceSuggestions.push('贴图文件过大，必须进行压缩优化');
            }
            // 🌍 环境模型优化建议
            if (environmentModelSize > 5 * 1024 * 1024) {
                performanceSuggestions.push('环境模型过大，必须进行优化或替换为低多边形版本');
            }
        }
        
        sceneResourceMap.push({
            sceneId: scene.id,
            sceneName: scene.name,
            sceneType: scene.type,
            resources: {
                models: usedModels,
                materials: usedMaterials,
                textures: usedTextures,
                environmentModel: environmentModel // 🌍 环境模型信息
            },
            statistics: {
                modelCount: usedModels.length,
                materialCount: usedMaterials.length,
                textureCount: usedTextures.length,
                totalResourceCount: resourceCount,
                totalModelSize: totalModelSize,
                totalTextureSize: totalTextureSize,
                totalSize: totalSize,
                hasEnvironmentModel: environmentModel !== null, // 🌍 是否有环境模型
                environmentModelSize: environmentModel ? environmentModel.size : 0 // 🌍 环境模型大小
            },
            performance: {
                score: performanceScore,
                level: performanceLevel,
                estimatedLoadTime: estimatedLoadTime,
                suggestions: performanceSuggestions
            }
        });
    });
    
    return sceneResourceMap;
}

module.exports = router;

